//
//  BIDActivityViewController.m
//  HJGJCommunity
//
//  Created by mal on 2017/5/25.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDActivityViewController.h"
#import "BIDActivitySectionHeaderView.h"
#import "BIDActivityCell.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "NSDate+Category.h"

#import "BIDActivityDetailViewController.h"

//活动类型
static NSString *activityTypeURL = @"activityTypeAndroid/list.action";
//活动列表
static NSString *activityListURL = @"activityAndroid/list.action";

@interface BIDActivityViewController ()<BIDBaseListViewDelegate, BIDActivitySectionHeaderViewDelegate, UITableViewDelegate, UITableViewDataSource>
{
    BIDActivitySectionHeaderView *_sectionHeaderView;
    BOOL _bRegister;
    //活动类型
    NSMutableArray *_activityTypeArr;
    //活动状态
    NSArray *_activityStatusArr;
    //菜单数据源
    NSArray *_menuArr;
    NSUInteger _curTypeIndex;
    NSUInteger _curStatusIndex;
    //数据源来自于活动类型还是活动状态
    NSUInteger _curKind;
    UITableView *_menuTableView;
    //菜单view的遮罩
    UIView *_maskView;
    //菜单是否已显示
    BOOL _isMenuShow;
}
@end

@implementation BIDActivityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"社区活动";
    _activityTypeArr = [NSMutableArray array];
    _activityStatusArr = @[@{@"name":@"全部", @"flag":@"0"},
                           @{@"name":@"报名中", @"flag":@"1"},
                           @{@"name":@"截止报名", @"flag":@"2"},
                           @{@"name":@"进行中", @"flag":@"3"},
                           @{@"name":@"已结束", @"flag":@"4"}];
    _curTypeIndex = 0;
    _curStatusIndex = 0;
    _curKind = 0;
    _isMenuShow = NO;
    //
    _sectionHeaderView = [[[NSBundle mainBundle] loadNibNamed:@"BIDActivitySectionHeaderView" owner:self options:nil] lastObject];
    _sectionHeaderView.delegate = self;
    //
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    _menuTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(_sectionHeaderView.frame), screenSize.width, 176.f)];
    _menuTableView.delegate = self;
    _menuTableView.dataSource = self;
    _menuTableView.tag = 101;
    //
    _maskView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(_sectionHeaderView.frame), screenSize.width, screenSize.height-64-CGRectGetHeight(_sectionHeaderView.frame))];
    [_maskView setBackgroundColor:RGBACOLOR(0, 0, 0, 0.7f)];
    _maskView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)];
    [_maskView addGestureRecognizer:tapGR];
    //
    self.myTableView.tableFooterView = [[UIView alloc] init];
    //
    [self fetchActivityType];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadData
{
    [self fetchActivityList];
}

- (void)tapGestureHandler:(UITapGestureRecognizer *)tapGR
{
    [self hideMenuView];
}

- (void)showMenuView
{
    _isMenuShow = YES;
    [self.view addSubview:_maskView];
    [self.view addSubview:_menuTableView];
    [_menuTableView reloadData];
}

- (void)hideMenuView
{
    _isMenuShow = NO;
    [_menuTableView removeFromSuperview];
    [_maskView removeFromSuperview];
}

/**
 获取活动列表
 */
- (void)fetchActivityList
{
    self.curPage++;
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], activityListURL];
    NSMutableString *strPost = [[NSMutableString alloc] initWithFormat:@"page=%ld&rows=%ld&memberId=%@", self.curPage, self.countPerPage, [AppDelegate getUserId]];
    if(_curTypeIndex != 0)
    {
        [strPost appendFormat:@"&searchParam.typeId=%@", _activityTypeArr[_curTypeIndex][@"id"]];
    }
    if(_curStatusIndex != 0)
    {
        [strPost appendFormat:@"&searchParam.states=%@", _activityStatusArr[_curStatusIndex][@"flag"]];
    }
    
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            NSArray *arr = responseDic[@"rows"];
            [self.dataSourceArr addObjectsFromArray:arr];
            if(self.dataSourceArr.count < self.curPage*self.countPerPage)
            {
                [self.myTableView hasNoMoreData];
            }
            else
            {
                [self.myTableView hasMoreData];
            }
            [self.myTableView reloadData];
        }
        [self autoDecideToShowEmptyView];
    }];
}

/**
 获取活动类型
 */
- (void)fetchActivityType
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], activityTypeURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"memberId=%@", [AppDelegate getUserId]];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
        }
        else
        {
            NSArray *arr = (NSArray *)responseDic;
            _activityTypeArr = [[NSMutableArray alloc] initWithArray:arr];
            [_activityTypeArr insertObject:@{@"name":@"全部"} atIndex:0];
            [self fetchActivityList];
        }
        [self.myTableView reloadData];
    }];
}

/**
 把活动时间转换为带有星期几的时间

 @param originDate <#originDate description#>
 @return <#return value description#>
 */
- (NSString *)transformTakeWeekDayFrom:(NSString *)originDate
{
    NSDateFormatter *dateFormatter = [NSDateFormatter dateFormatterWithFormat:@"yyyy-MM-dd HH-mm"];
    NSDate *date = [dateFormatter dateFromString:originDate];
    NSInteger weekDay = [date weekday];
    NSString *strWeekDay = @"";
    switch(weekDay)
    {
        case 1:
        {
            strWeekDay = @"周天";
        }
            break;
        case 2:
        {
            strWeekDay = @"周一";
        }
            break;
        case 3:
        {
            strWeekDay = @"周二";
        }
            break;
        case 4:
        {
            strWeekDay = @"周三";
        }
            break;
        case 5:
        {
            strWeekDay = @"周四";
        }
            break;
        case 6:
        {
            strWeekDay = @"周五";
        }
            break;
        case 7:
        {
            strWeekDay = @"周六";
        }
            break;
    }
    NSArray *arr = [originDate componentsSeparatedByString:@" "];
    NSString *strDes = [[NSString alloc] initWithFormat:@"%@ (%@) %@开始", arr[0], strWeekDay, arr[1]];
    return strDes;
}

#pragma mark - BIDActivitySectionHeaderViewDelegate
- (void)showMenuWithType:(NSUInteger)type
{
    if(_curKind == type && _isMenuShow)
    {
        [self hideMenuView];
        return;
    }
    _curKind = type;
    if(type == 0)
    {
        //活动类型
        _menuArr = [[NSArray alloc] initWithArray:_activityTypeArr];
    }
    else
    {
        //活动状态
        _menuArr = [[NSArray alloc] initWithArray:_activityStatusArr];
    }
    CGRect frame = _menuTableView.frame;
    frame.size.height = _menuArr.count * 45;
    _menuTableView.frame = frame;
    [self showMenuView];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView.tag == 101)
    {
        if(_curKind == 0)
        {
            return _activityTypeArr.count;
        }
        else
        {
            return _activityStatusArr.count;
        }
    }
    else
    {
        return self.dataSourceArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *identifier = @"identifier";
    static NSString *menuIdentifier = @"menu";
    NSUInteger row = indexPath.row;
    if(tableView.tag == 101)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:menuIdentifier];
        if(!cell)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:menuIdentifier];
        }
        NSDictionary *dic = _menuArr[row];
        cell.textLabel.text = dic[@"name"];
        cell.accessoryType = UITableViewCellAccessoryNone;
        NSUInteger index = _curKind==0? _curTypeIndex : _curStatusIndex;
        if(index == row)
        {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
    }
    else
    {
        if(!_bRegister)
        {
            _bRegister = YES;
            UINib *nib = [UINib nibWithNibName:@"BIDActivityCell" bundle:nil];
            [tableView registerNib:nib forCellReuseIdentifier:identifier];
        }
        BIDActivityCell *activityCell = [tableView dequeueReusableCellWithIdentifier:identifier];
        NSDictionary *activityDic = self.dataSourceArr[row];
        //活动标题
        activityCell.titleLabel.text = activityDic[@"title"];
        //活动标题图
        NSString *strFilePath = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], activityDic[@"titleImage"]];
        [activityCell.imgView setImageWithURL:[NSURL URLWithString:strFilePath] placeholderImage:[UIImage imageNamed:@"slide_placeholder.png"]];
        NSLog(@"%@", strFilePath);
        //活动状态
        NSNumber *stateValue = activityDic[@"states"];
        UIColor *color;
        if([stateValue intValue]==2 || [stateValue intValue]==4)
        {
            color = RGBACOLOR(110, 110, 110, 0.7f);
        }
        else
        {
            color = RGBACOLOR(60, 120, 231, 0.7f);
        }
        [activityCell.statusLabel setBackgroundColor:color];
        activityCell.statusLabel.text = activityDic[@"statesName"];
        //活动已报名人数
        NSNumber *applyCountValue = activityDic[@"signNum"];
        activityCell.applyLabel.text = [[NSString alloc] initWithFormat:@"已报名人数%@人", applyCountValue];
        activityCell.timeLabel.text = [self transformTakeWeekDayFrom:activityDic[@"startTime"]];
        //是否需要费用
        NSNumber *isNeedPayValue = activityDic[@"isPay"];
        NSString *strCost = [isNeedPayValue intValue]==0 ? @"免费" : activityDic[@"price"];
        activityCell.costLabel.text = [[NSString alloc] initWithFormat:@"%@", strCost];
        cell = activityCell;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSUInteger row = indexPath.row;
    if(tableView.tag == 101)
    {
        if(_curKind == 0)
        {
            if(_curTypeIndex != row)
            {
                self.curPage = 0;
                [self.dataSourceArr removeAllObjects];
                _curTypeIndex = row;
                [self fetchActivityList];
            }
        }
        else
        {
            if(_curStatusIndex != row)
            {
                [self.dataSourceArr removeAllObjects];
                self.curPage = 0;
                _curStatusIndex = row;
                [self fetchActivityList];
            }
        }
        [self hideMenuView];
    }
    else
    {
        //进入活动详情页面
        NSDictionary *dic = self.dataSourceArr[row];
        BIDActivityDetailViewController *vc = [[BIDActivityDetailViewController alloc] initWithNibName:@"BIDActivityDetailViewController" bundle:nil];
        vc.activityID = dic[@"id"];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView.tag == 101)
    {
        return 44.f;
    }
    else
    {
        return 321.f;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(tableView.tag == 101)
    {
        return 0.f;
    }
    else
    {
        return 45.f;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(_sectionHeaderView)
    {
        return _sectionHeaderView;
    }
    else
    {
        return nil;
    }
}

@end
